<template>
  <a-spin :spinning="uploadLoading">
    <div class="translation-container">
      <div class="input-section">
        <div>
          <a-select v-model:value="source" style="width: 150px">
            <a-select-option value="auto">自动检测</a-select-option>
            <a-select-option v-for="item in languages" :value="item.key">
              {{ item.value }}
            </a-select-option>
          </a-select>
          <span style="margin: 0 20px"> -> </span>
          <a-select v-model:value="target" style="width: 150px">
            <a-select-option v-for="item in languages" :value="item.key">
              {{ item.value }}
            </a-select-option>
          </a-select>
        </div>
        <div style="margin-top: 20px">
          <a-textarea
            :disabled="loading"
            v-model:value="input"
            placeholder="请输入需要翻译的内容"
            :auto-size="{ minRows: 6, maxRows: 10 }"
            :bordered="false"
            @keydown.enter="pressEnter"
            autofocus
            class="input-textarea"
          />

          <!-- 工具栏 -->
          <div class="toolbar">
            <!-- 上传文件 -->
            <a-upload :custom-request="customRequest" :show-upload-list="false" :max-count="1">
              <a-tooltip title="上传文档（支持 PDF、DOCX、TXT，仅提取文字）">
                <span class="tool-btn">
                  <LinkOutlined />
                </span>
              </a-tooltip>
            </a-upload>

            <!-- 清空输入 -->
            <a-tooltip title="清空输入">
              <span class="tool-btn" @click="clearInput">
                <DeleteOutlined />
              </span>
            </a-tooltip>

            <!-- 术语表开关 -->
            <a-tooltip title="自定义术语表">
              <span class="tool-btn" @click="toggleGlossary">
                <BookOutlined />
              </span>
            </a-tooltip>

            <!-- 提交按钮 -->
            <a-button
              type="primary"
              size="small"
              @click="submit"
              :loading="loading"
              class="submit-btn"
            >
              {{ loading ? '翻译中...' : '发送' }}
            </a-button>
          </div>

          <!-- 术语表抽屉 -->
          <a-drawer
            title="自定义术语表"
            placement="right"
            :width="600"
            :visible="glossaryVisible"
            @close="glossaryVisible = false"
          >
            <glossary-drawer v-if="glossaryVisible" @close="glossaryVisible = false" />
          </a-drawer>
        </div>
      </div>
      <!-- 右侧输出区 -->
      <div class="output-section">
        <div class="output-wrapper">
          <MarkdownRenderer v-if="output" :source="output" />
          <div v-else class="placeholder">翻译结果将显示在这里...</div>
        </div>

        <!-- 控制按钮 -->
        <div class="output-footer">
          <a-tooltip title="复制翻译结果">
            <a-button size="small" @click="copyOutput" class="action-btn">
              <CopyOutlined />
            </a-button>
          </a-tooltip>
          <a-tooltip title="停止翻译">
            <a-button size="small" danger @click="stop" :disabled="!loading" class="action-btn">
              <StopOutlined />
            </a-button>
          </a-tooltip>
        </div>
      </div>
    </div>
  </a-spin>
</template>

<script setup>
import Http from '@/api/http'
import { isLogin } from '@/stores/user'
import GlossaryDrawer from '@/views/component/GlossaryDrawer.vue'
import MarkdownRenderer from '@/views/component/MarkdownRenderer.vue'
import {
  BookOutlined,
  CopyOutlined,
  DeleteOutlined,
  LinkOutlined,
  StopOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { onMounted, onUnmounted, ref } from 'vue'

const languages = [
  { key: 'English', value: '英语' },
  { key: 'Chinese', value: '简体中文' },
  { key: 'Traditional Chinese', value: '繁体中文' },
  { key: 'Russian', value: '俄语' },
  { key: 'Japanese', value: '日语' },
  { key: 'Korean', value: '韩语' },
  { key: 'Spanish', value: '西班牙语' },
  { key: 'French', value: '法语' },
  { key: 'Portuguese', value: '葡萄牙语' },
  { key: 'German', value: '德语' },
  { key: 'Italian', value: '意大利语' },
  { key: 'Thai', value: '泰语' },
  { key: 'Vietnamese', value: '越南语' },
  { key: 'Indonesian', value: '印度尼西亚语' },
  { key: 'Malay', value: '马来语' },
  { key: 'Arabic', value: '阿拉伯语' },
  { key: 'Hindi', value: '印地语' },
  { key: 'Hebrew', value: '希伯来语' },
  { key: 'Burmese', value: '缅甸语' },
  { key: 'Tamil', value: '泰米尔语' },
  { key: 'Urdu', value: '乌尔都语' },
  { key: 'Bengali', value: '孟加拉语' },
  { key: 'Polish', value: '波兰语' },
  { key: 'Dutch', value: '荷兰语' },
  { key: 'Romanian', value: '罗马尼亚语' },
  { key: 'Turkish', value: '土耳其语' },
  { key: 'Khmer', value: '高棉语' },
  { key: 'Lao', value: '老挝语' },
  { key: 'Cantonese', value: '粤语' },
  { key: 'Czech', value: '捷克语' },
  { key: 'Greek', value: '希腊语' },
  { key: 'Swedish', value: '瑞典语' },
  { key: 'Hungarian', value: '匈牙利语' },
  { key: 'Danish', value: '丹麦语' },
  { key: 'Finnish', value: '芬兰语' },
  { key: 'Ukrainian', value: '乌克兰语' },
  { key: 'Bulgarian', value: '保加利亚语' },
  { key: 'Serbian', value: '塞尔维亚语' },
  { key: 'Telugu', value: '泰卢固语' },
  { key: 'Afrikaans', value: '南非荷兰语' },
  { key: 'Armenian', value: '亚美尼亚语' },
  { key: 'Assamese', value: '阿萨姆语' },
  { key: 'Asturian', value: '阿斯图里亚斯语' },
  { key: 'Basque', value: '巴斯克语' },
  { key: 'Belarusian', value: '白俄罗斯语' },
  { key: 'Bosnian', value: '波斯尼亚语' },
  { key: 'Catalan', value: '加泰罗尼亚语' },
  { key: 'Cebuano', value: '宿务语' },
  { key: 'Croatian', value: '克罗地亚语' },
  { key: 'Egyptian Arabic', value: '埃及阿拉伯语' },
  { key: 'Estonian', value: '爱沙尼亚语' },
  { key: 'Galician', value: '加利西亚语' },
  { key: 'Georgian', value: '格鲁吉亚语' },
  { key: 'Gujarati', value: '古吉拉特语' },
  { key: 'Icelandic', value: '冰岛语' },
  { key: 'Javanese', value: '爪哇语' },
  { key: 'Kannada', value: '卡纳达语' },
  { key: 'Kazakh', value: '哈萨克语' },
  { key: 'Latvian', value: '拉脱维亚语' },
  { key: 'Lithuanian', value: '立陶宛语' },
  { key: 'Luxembourgish', value: '卢森堡语' },
  { key: 'Macedonian', value: '马其顿语' },
  { key: 'Maithili', value: '马加希语' },
  { key: 'Maltese', value: '马耳他语' },
  { key: 'Marathi', value: '马拉地语' },
  { key: 'Mesopotamian Arabic', value: '美索不达米亚阿拉伯语' },
  { key: 'Moroccan Arabic', value: '摩洛哥阿拉伯语' },
  { key: 'Najdi Arabic', value: '内志阿拉伯语' },
  { key: 'Nepali', value: '尼泊尔语' },
  { key: 'North Azerbaijani', value: '北阿塞拜疆语' },
  { key: 'North Levantine Arabic', value: '北黎凡特阿拉伯语' },
  { key: 'Northern Uzbek', value: '北乌兹别克语' },
  { key: 'Norwegian Bokmål', value: '书面语挪威语' },
  { key: 'Norwegian Nynorsk', value: '新挪威语' },
  { key: 'Occitan', value: '奥克语' },
  { key: 'Odia', value: '奥里亚语' },
  { key: 'Pangasinan', value: '邦阿西楠语' },
  { key: 'Sicilian', value: '西西里语' },
  { key: 'Sindhi', value: '信德语' },
  { key: 'Sinhala', value: '僧伽罗语' },
  { key: 'Slovak', value: '斯洛伐克语' },
  { key: 'Slovenian', value: '斯洛文尼亚语' },
  { key: 'South Levantine Arabic', value: '南黎凡特阿拉伯语' },
  { key: 'Swahili', value: '斯瓦希里语' },
  { key: 'Tagalog', value: '他加禄语' },
  { key: 'Ta’izzi-Adeni Arabic', value: '塔伊兹-亚丁阿拉伯语' },
  { key: 'Tosk Albanian', value: '托斯克阿尔巴尼亚语' },
  { key: 'Tunisian Arabic', value: '突尼斯阿拉伯语' },
  { key: 'Venetian', value: '威尼斯语' },
  { key: 'Waray', value: '瓦莱语' },
  { key: 'Welsh', value: '威尔士语' },
  { key: 'Western Persian', value: '西波斯语' }
]
const input = ref('')
const output = ref('')
const loading = ref(false)
const uploadLoading = ref(false)
const stopFlag = ref(false)
const source = ref('auto')
const target = ref('Chinese')
const clientId = ref(null)

// 术语表相关
const glossaryVisible = ref(false)

// SSE 实例
let eventSource = null

// ========== 方法定义 ==========

// 打开术语表
const toggleGlossary = () => {
  glossaryVisible.value = true
}

// 清空输入
const clearInput = () => {
  input.value = ''
}

// 复制输出
const copyOutput = async () => {
  if (!output.value) {
    message.warning('没有可复制的内容')
    return
  }
  try {
    await navigator.clipboard.writeText(output.value)
    message.success('已复制到剪贴板')
  } catch (err) {
    message.error('复制失败')
  }
}

// 回车处理
const pressEnter = (e) => {
  if (e.keyCode === 13) {
    if (e.shiftKey) {
      // Shift + Enter：换行
      return
    } else {
      // Enter：提交
      e.preventDefault()
      submit()
    }
  }
}

// 提交翻译请求
const submit = () => {
  if (loading.value) {
    message.warning('请等待当前翻译完成')
    return
  }
  if (!input.value.trim()) return

  output.value = ''
  loading.value = true
  stopFlag.value = false
  const requestParams = {
    chatId: generateId(),
    clientId: clientId.value,
    content: input.value,
    source: source.value,
    target: target.value
  }

  Http.post('/api/agent/translation', requestParams)
}

const customRequest = ({ file }) => {
  const formData = new FormData()
  formData.append('file', file)
  uploadLoading.value = true
  Http.post('/api/file/readFile', formData)
    .then((res) => {
      input.value = res
    })
    .catch((err) => {
      message.error('文件解析失败')
    })
    .finally((res) => {
      uploadLoading.value = false
    })
}

// 停止 SSE 流
const stop = () => {
  stopFlag.value = true
  loading.value = false
  message.info('已停止接收翻译')
}

function generateId() {
  const timestamp = Date.now() // 毫秒级时间戳
  const randomNum = Math.floor(Math.random() * 10000) // 0-9999 的随机数
  return `${timestamp}${randomNum}`
}

// ========== 生命周期 ==========
onMounted(() => {
  if (!isLogin()) return
  clientId.value = generateId()
  const sseUrl = Http.baseUrl + '/sse/event/connect?clientId=' + clientId.value
  eventSource = new EventSource(sseUrl)
  eventSource.onmessage = (event) => {
    if (event.data === 'event: stop' || stopFlag.value === true) {
      loading.value = false
      return
    }

    try {
      const data = JSON.parse(event.data)
      if (data.content) {
        output.value = data.content
      }
    } catch (err) {}
  }

  eventSource.addEventListener('complete', () => {
    loading.value = false
  })

  eventSource.onerror = (err) => {
    loading.value = false
  }
})

onUnmounted(() => {
  if (eventSource) {
    eventSource.close()
  }
})
</script>

<style scoped>
.translation-container {
  display: flex;
  height: 100vh;
  gap: 20px;
  padding: 20px;
  background: #f9faff;
  border-radius: 12px;
  font-family: 'Segoe UI', sans-serif;
}

.input-section,
.output-section {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.input-textarea {
  flex: 1;
  margin-bottom: 12px;
  font-size: 15px;
  padding: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.toolbar {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 0;
}

.tool-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 36px;
  height: 36px;
  border-radius: 8px;
  color: #595959;
  cursor: pointer;
  transition: all 0.2s;
}

.tool-btn:hover {
  background: #e6f7ff;
  color: #1890ff;
}

.submit-btn {
  margin-left: auto;
  height: 36px;
}

.output-section {
  border-left: 1px solid #e8e8e8;
  padding-left: 20px;
}

.output-wrapper {
  flex: 1;
  background: #fff;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  overflow-y: auto;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  font-size: 15px;
  line-height: 1.7;
}

.placeholder {
  color: #999;
  font-style: italic;
}

.output-footer {
  margin-top: 12px;
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

.action-btn {
  width: 36px;
}
</style>
